<template>
  <div class="search">
    <div class="search-input-warp">
      <SearchInput v-model="query" placeholder="搜索歌曲丶歌手" />
    </div>

    <div class="search-content" ref="scrollRef" v-show="!query">
      <div class="hot-keys">
        <h1 class="title">热门搜索</h1>
        <ul>
          <li
            class="item"
            v-for="item in hotKeys"
            :key="item.id"
            @click="addQuery(item.key)"
          >
            <span>{{ item.key }}</span>
          </li>
        </ul>
      </div>
      <SearchList
        @addQuery="addQuery"
        ref="SearchList"
        showDelete
        :query="query"
      />
    </div>
    <div class="search-result" v-show="query">
      <Suggest :query="query" @select-song="selectSong"></Suggest>
    </div>
  </div>
</template>
<script>
import SearchInput from '@/components/Search/SearchInput'
import SearchList from '@/components/Search/SearchList'
import Suggest from '@/components/Search/Suggest.vue'

import { getHotKeys } from '@/service/search'

import { ref, watch } from 'vue'
import { useStore } from 'vuex'
import { Toast } from 'vant'
export default {
  name: 'search',
  components: {
    SearchInput,
    Suggest,
    SearchList
  },
  setup() {
    const store = useStore()
    // 搜索参数
    const query = ref('')
    const hotKeys = ref([])
    const SearchList = ref(null)
    getHotKeys().then(res => {
      hotKeys.value = res.hotKeys
    })
    watch(query, (newVal, oldVal) => {
      if (!newVal) return
      if (newVal.trim() !== oldVal.trim()) {
        SearchList.value.emitAddHistory(newVal)
        query.value = newVal
        console.log(newVal, oldVal)
      }
    })

    // 点击关键字
    function addQuery(key) {
      query.value = key
    }

    function selectSong(item) {
      console.log(item)
      addSong(item)
    }
    function addSong(song) {
      showMessage()
      setTimeout(() => {
        store.dispatch('addSong', song)
      }, 1500)
    }

    function showMessage() {
      Toast('1首歌曲已经添加到播放列表')
    }

    return {
      selectSong,
      SearchList,
      query,
      hotKeys,
      addQuery
    }
  }
}
</script>
<style lang="scss" scoped>
.search {
  width: 100vw;
  .search-input-warp {
    width: 100%;
    height: 54px;
  }
  .search-content {
    .hot-keys {
      margin: 0 20px 20px;
      .title {
        margin-bottom: 20px;
        font-size: $font-size-medium;
        color: $color-text-l;
      }
      .item {
        display: inline-block;
        padding: 5px 10px;
        margin: 0 20px 10px 0;
        border-radius: 6px;
        background: $color-highlight-background;
        font-size: $font-size-medium;
        color: $color-text-d;
      }
    }
  }
}
</style>
